//
// Created by pulsarv on 19-5-2.
//

#include <rc_network/rc_tcp_client.h>
#include <iostream>
boost::asio::io_service service;

boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string("127.0.0.1"), 9002);


size_t read_complete(char * buf, const boost::system::error_code & err, size_t bytes) {
    if (err) return 0;
    bool found = std::find(buf, buf + bytes, '\n') < buf + bytes;
    // 一个一个字符的读取，直到回车, 不缓存
    return found ? 0 : 1;
}


void sync_echo(std::string msg) {
    msg += "\n";
    boost::asio::ip::tcp::socket sock(service);
    sock.connect(ep);
    sock.write_some(boost::asio::buffer(msg));
    char buf[1024];
    int bytes = read(sock, boost::asio::buffer(buf), boost::bind(read_complete, buf, _1, _2));
    std::string copy(buf, bytes - 1);
    msg = msg.substr(0, msg.size() - 1);
    std::cout << "server echoed our " << msg << ": "
              << (copy == msg ? "OK" : "FAIL") << std::endl;
    sock.close();
}
